#include "myqq.h"
#include "ui_myqq.h"
#include "tcpclientwidget.h"

#include <QTcpSocket>
#include <QMessageBox>//用于小窗口弹出信息
#include <QDebug>
#include <QHostAddress>

Myqq::Myqq(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Myqq)
{
    ui->setupUi(this);

    //setWindowFlags(Qt::FramelessWindowHint);
}

Myqq::~Myqq()
{
    delete ui;
}

void Myqq:: sendData(QString name, QString password)
{
    socket = new QTcpSocket();
    socket->connectToHost(QHostAddress("127.0.0.1"), 9999);
    if(!socket->waitForConnected())
    {
        return ;
    }
    QString msg = name + "#*#" + password;
    socket->write(msg.toLatin1(), msg.toLatin1().length());
    if(!socket->waitForReadyRead())
    {
        return;
    }

    QByteArray ba;
    ba.resize(socket->bytesAvailable());
    socket->read(ba.data(), ba.size());
    qDebug() << "in myqq client : " << ba.data();
    if(ba == "Success")
    {
        TcpClientWidget *w = new TcpClientWidget();
        w->show();
        close();
    }
    else
    {
        QMessageBox::warning(this, "Error", "Sorry, account or password error !");
    }

}

void Myqq::on_pushButtonLogin_clicked()
{
    if(ui->lineEditAccount->text().isEmpty())
    {
        QMessageBox::critical(this, "account", "Account is Empty!");
        return;
    }

    if(ui->lineEditPassword->text().isEmpty())
    {
        QMessageBox::critical(this, "password", "Password is Empty!");
        return;
    }


    sendData(QString(ui->lineEditAccount->text()), QString(ui->lineEditPassword->text()));
}


#if 0
void Myqq::on_pushButton_clicked()
{
#if 0
    registerDialog regDialog;
    regDialog.show();

    regDialog.exec();

    if(regDialog.exec() == QDialog::Accepted)//弹出窗口信息
    {
        if(regDialog.isValued())
        {
            //qDebug() << regDialog.name() << regDialog.passwd();
            //md5
            //save information to database

            QString sql = QString("insert into student values(1, '%1', '%2', '%3', '%4')")
                    .arg(regDialog.name())
                    .arg(regDialog.passwd())
                    .arg(regDialog.email())
                    .arg(regDialog.phone());
            qDebug() << sql;

            bool ok = query.exec(sql);
            if(!ok)
            {
                qDebug() << query.lastError();
            }
        }
    }
#endif
}
#endif

void Myqq::on_pushButtonRegister_clicked()
{
    RegisterBox *registerbox = new RegisterBox();
    registerbox->show();
    close();
}
